using UnityEngine;
using System.Collections.Generic;

public class TrackPoint : MonoBehaviour
{
    public List<TrackPoint> nextPoints = new List<TrackPoint>();  // 所有可能的下一个轨道点

    public bool IsStop;//路过这里的时候是否强制停车
    public bool IsDead;//到达这里的时候，游戏失败
    public int LevelIndex;
    
    // 根据方向选择下一个轨道点
    public TrackPoint GetNextPoint(Vector3 direction)
    {
        if (nextPoints.Count == 0) return null;
        if (nextPoints.Count == 1) return nextPoints[0];

        TrackPoint bestPoint = nextPoints[0];
        float bestAngle = Vector3.Angle(direction, (bestPoint.transform.position - transform.position).normalized);

        // 选择与给定方向夹角最小的轨道点
        foreach (var point in nextPoints)
        {
            float angle = Vector3.Angle(direction, (point.transform.position - transform.position).normalized);
            if (angle < bestAngle)
            {
                bestAngle = angle;
                bestPoint = point;
            }
        }

        return bestPoint;
    }

    // 添加新的下一个轨道点
    public void AddNextPoint(TrackPoint point)
    {
        if (!nextPoints.Contains(point))
        {
            nextPoints.Add(point);
        }
    }

    // 移除下一个轨道点
    public void RemoveNextPoint(TrackPoint point)
    {
        nextPoints.Remove(point);
    }
    
    private void OnDrawGizmos()
    {
        // 在Scene视图中绘制所有可能的轨道连线
        foreach (var point in nextPoints)
        {
            if (point != null)
            {
                Gizmos.color = Color.yellow;
                Gizmos.DrawLine(transform.position, point.transform.position);
                
                // 在分叉点绘制一个小球，方便识别
                if (nextPoints.Count > 1)
                {
                    Gizmos.color = Color.red;
                    Gizmos.DrawSphere(transform.position, 0.3f);
                }
            }
        }
    }
}